<?php

namespace App\Services;

use App\Models\Community;
use App\Models\ElementModel;
use App\Models\FloorModel;
use App\Models\HouseModel;
use App\Models\RoomModel;
use App\Traits\HelperTrait;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class HouseService extends BaseService
{
    use HelperTrait;

    protected $error_msg = '';

    /**
     * Notes: 获取楼栋列表
     * User: lstink
     * Date: 2021/2/4
     * Time: 10:48 上午
     * @param $where
     * @return mixed
     */
    public function getHouseList($where, $param)
    {
        return HouseModel::with('community')->where($where)->where(function ($query) use ($param) {
            if (!empty($param['house_num'])) {
                $query->where('house_num', $param['house_num']);
            }
            if (!empty($param['c_id'])) {
                $query->where('c_id', $param['c_id']);
            }
        })->orderBy('house_num')->paginate($param['per_page'] ?? 30);
    }

    /**
     * Notes: 添加
     * User: lstink
     * Date: 2021/3/16
     * Time: 2:46 下午
     * @param $data
     * @param $estate_id
     * @return bool|mixed
     */
    public function addHouse($data, $estate_id)
    {
        //验证数据
        $validator = Validator::make($data, [
            'community_id' => 'required',
            'house'        => 'required',
        ], [
            'community_id.required' => '请选择小区！',
            'house.required'        => '请填写楼号！',
        ]);
        if ($validator->fails()) {
            $this->error_msg = $validator->errors()->first();
            return false;
        }
        //处理楼层信息
        return $this->handleHouse($data, $estate_id);
    }

    /**
     * Notes: 处理楼栋数据
     * User: lstink
     * Date: 2021/2/4
     * Time: 10:00 上午
     * @param $data
     * @param $estate_id
     * @return mixed
     */
    protected function handleHouse($data, $estate_id)
    {
        $house = [];
        if ($this->isMul($data['house'])) {
            $arr = explode('-', $data['house']);
            $arr = array_filter($arr);
            //批量添加
            for ($i = $arr[0]; $i <= $arr[1]; $i++) {
                $house[] = [
                    'estate_id' => $estate_id,
                    'c_id'      => $data['community_id'],
                    'house_num' => $i,
                ];
            }
        } else {
            //单个添加
            $house[] = [
                'estate_id' => $estate_id,
                'c_id'      => $data['community_id'],
                'house_num' => $data['house'],
            ];
        }

        DB::beginTransaction();
        try {
            HouseModel::insert($house);
            DB::commit();
        } catch (\Throwable $e) {
            DB::rollBack();
            if (count($house) > 1) {
                $this->error_msg = '存在已有楼栋号，请检查';
            } else {
                $this->error_msg = '该楼号已存在，请勿重复添加';
            }
            return false;
        }

        return true;
    }

    /**
     * Notes: 判断是否为批量添加
     * User: lstink
     * Date: 2021/2/3
     * Time: 3:57 下午
     * @param $value
     * @return bool
     */
    protected function isMul($value)
    {
        if (strpos($value, '-') === false) {
            return false;
        }

        return true;
    }

    /**
     * Notes: 获取错误信息
     * User: lstink
     * Date: 2021/2/4
     * Time: 10:02 上午
     * @return string
     */
    public function getMessage()
    {
        return $this->error_msg;
    }

    /**
     * 获取所有的额小区
     * @param $id
     * @return mixed
     * @author ypp
     * @date 2021/03/03
     */
    public function getAllCommunity($id,$cid,$areaid)
    {
        return (new Community())->getSelect(['province' => $id,'city' => $cid,'area' => $areaid,'status'=>1], 'community_id');
    }
    /**
     * Notes: 获取小区的所有楼栋
     * User: lstink
     * Date: 2021/2/4
     * Time: 4:20 下午
     * @param $id
     * @return mixed
     */
    public function getHouseListByCommunity($id)
    {
        return (new HouseModel)->getSelect(['c_id' => $id], 'house_num');
    }

    /**
     * Notes: 获取楼栋的所有单元
     * User: lstink
     * Date: 2021/2/5
     * Time: 5:09 下午
     * @param $id
     * @return mixed
     */
    public function getElementListByHouse($id)
    {
        return (new ElementModel)->getSelect(['h_id' => $id], 'element_num');
    }

    /**
     * Notes: 获取单元的所有楼层
     * User: lstink
     * Date: 2021/2/5
     * Time: 5:10 下午
     * @param $id
     * @return mixed
     */
    public function getFloorListByElement($id)
    {
        return (new FloorModel)->getSelect(['e_id' => $id], 'floor');
    }

    /**
     * Notes: 获取单元的所有楼层
     * User: lstink
     * Date: 2021/2/5
     * Time: 5:10 下午
     * @param $id
     * @return mixed
     */
    public function getRoomListByFloor($id)
    {
        return (new RoomModel())->getSelect(['f_id' => $id], 'room');
    }

    /**
     * Notes: 根据用户id获取房间小区等信息
     * User: lstink
     * Date: 2021/3/4
     * Time: 4:33 下午
     * @param $user_id
     * @return array
     */
    public function getRoomInfoByUserId($user_id): array
    {
        $info = RoomModel::whereHas('user', function ($query) use ($user_id) {
            $query->where('id', $user_id);
        })->with(['community', 'house', 'element', 'floor', 'user'])->first();
        if (!$info) {
            return $this->format_error('暂无信息');
        }
        //拼装数据
        $arr = [
            'community' => $info->community->community_name,
            'roomInfo' => $info->house->house_num . '号楼-' . $info->element->element_num . '单元-' . $info->floor->floor . '层-' . $info->room,
        ];
        return $this->format($arr);
    }
}
